package com.example.testnetty.nettyserver;


import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.example.testnetty.MainActivity;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Iterator;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class ServerChannel extends SimpleChannelInboundHandler<String> {

    Context context;

    boolean isTime = false;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private JSONObject jsonObject;

    public ServerChannel(Context context) {

        this.context = context;

    }

    /**
     * 通道 活跃， 正常通信。 新客户端连接
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.e("ServerChannel", simpleDateFormat.format(System.currentTimeMillis()) + "新连接" + ctx.channel().remoteAddress());
        //添加管道到ChanelGroup
        ChannelGroups.add(ctx.channel());
        // ChannelMap.Add("", ctx.channel().id());
        Log.e("ServerChannel", "当前客户端总数:" + ChannelGroups.size() + "Map大小" + ChannelMap.size());
        Iterator<Channel> allChanel = ChannelGroups.allChanel();
        while (allChanel.hasNext()) {
            Channel channel = allChanel.next();
            Log.e("", "已连接对象: " + channel.remoteAddress().toString());
        }
        super.channelActive(ctx);

    }

    /**
     * 建立连接后在关闭管道，客户端断开
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.e("ServerChannel", simpleDateFormat.format(System.currentTimeMillis()) + "连接关闭" + ctx.channel().remoteAddress());
        ChannelGroups.discard(ctx.channel());
        super.channelInactive(ctx);
    }



    /**
     * @param channelHandlerContext
     * @param data                  类型与继承的SimpleChannelInboundHandler<String> 的参数有关
     * @throws Exception
     */
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String data) throws Exception {
        Log.e("ServerChannel", "来自" + channelHandlerContext.channel().remoteAddress() + "的消息:" + data);
        if (!TextUtils.isEmpty(data)) {
////            doSomeThing(data, channelHandlerContext);
//
            toActivity(data);
        }

    }

    /*
     *发送到android页面上
     * */
    private void toActivity(String data) {

        Bundle bundle = new Bundle();

        bundle.putString("data", data);

        Message message = MainActivity.handler.obtainMessage();

        message.what = 0;

        message.setData(bundle);

        message.sendToTarget();

    }

    private void doSomeThing(String data, ChannelHandlerContext channelHandlerContext) {

        Log.e("ServerChannel", "数据: " + data);

//        String str = channelHandlerContext.channel().remoteAddress().toString().replace("/", "").trim();
//        str = str.substring(0, str.indexOf(":"));
//        if (data.trim().equals("{\"method\":\"heartbeat\"}")) {
//            Log.e("ServerChannel","心跳数据" + data);
//            return;
//        } else {
//            Log.e("ServerChannel","数据: " + data);
//        }
//        String json = "{\"cmd\":\"2\",\"token\":\"780e91422bfa8a228be4347cdb7128e4\",\"isFlag\":\"true\"}";
//        try {
//            jsonObject = new JSONObject(data);
//            if (false) {
//
//            } else {
//                channelHandlerContext.channel().writeAndFlush("Unified security verification error.\r\n");
//                return;
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//            channelHandlerContext.channel().writeAndFlush("Data format error, you will force the offline.\r\n");
//            channelHandlerContext.channel().close();
//        }
    }


    //异常捕获
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Log.e("ServerChannel", simpleDateFormat.format(System.currentTimeMillis()) + "ClientHandler.exceptionCaught");
        cause.printStackTrace();
        //出现异常，移除改通道
    }


    //心跳超时操作

    String host = null;

    @Override
    public void userEventTriggered(final ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        host = ctx.channel().remoteAddress().toString().replace("/", "").trim();
        host = host.substring(0, host.indexOf(":"));
        if (evt instanceof IdleStateEvent) {
            //  LogUtil.E(simpleDateFormat.format(System.currentTimeMillis()) + "读写状态" + event.state());
            if (event.state() == IdleState.ALL_IDLE) {
                // TODO: 2018/3/26 长时间没有读写操作,关闭此通道  减少服务器压力。

            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
